package com.hqyj.tmall.service.serviceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.mapper.ProductImageMapper;
import com.hqyj.mapper.ProductMapper;
import com.hqyj.pojo.Product;
import com.hqyj.pojo.ProductImage;
import com.hqyj.tmall.service.TmallService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class TmallServiceImpl implements TmallService {

    @Resource
    private ProductMapper productMapper;


    @Resource
    private ProductImageMapper productImageMapper;

    @Override
    public Map<String, Object> findBySeekName(String seekName, Integer page, Integer row) {
        // 返回参数
        HashMap<String, Object> map = new HashMap<>();

        //初始化example 对象
        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();

        // 设置模糊查询
        if (!StringUtils.isEmpty(seekName)) {
            criteria.andLike("name", "%" + seekName + "%").orLike("subTitle", seekName).orLike("seller", "%" + seekName + "%");
        }

        // 添加分页条件
        PageHelper.startPage(page, row);

        // 查询
        List<Product> products = this.productMapper.selectByExample(example);

        // 的到结果数据
        PageInfo<Product> pageInfo = new PageInfo<>(products);

        // 如果商品不为空查询对应的图片
        LinkedList<ProductImage> productImages = new LinkedList<>();
        if (!CollectionUtils.isEmpty(pageInfo.getList())) {
            for (Product product : pageInfo.getList()) {
                Example exampleImg = new Example(ProductImage.class);
                Example.Criteria criteriaImg = exampleImg.createCriteria();
                criteriaImg.andEqualTo("productId", product.getId()).andEqualTo("type", 0);
                ProductImage productImage = this.productImageMapper.selectOneByExample(exampleImg);
                productImages.add(productImage);
            }
        }

        // 封装返回数据
        map.put("pageInfo", pageInfo);
        map.put("pageImges", productImages);
        return map;
    }


}
